<template>
  <view class="container w100p common_wrap no-bg vh-100">
    <CommonHeader
      :title="$t('确认订单')"
      color="#262728"
      :is-right="false"
      @goback="goback"
    ></CommonHeader>
    <view class="bg-color"></view>

    <!-- 收货地址 -->
    <view class="address-wrapper">
      <view class="top-section">
        <view class="address">{{ $t("运输路线2") }}</view>
        <view class="change-address" @click="onChangeAddress">{{
          $t("修改地址")
        }}</view>
      </view>
      <!-- base-info -->
      <view class="address-base" @click="onChangeAddress">
        <view class="person-base">
          <image src="/static/mt-li/person.png" />
          <!-- <text>{{ deliveryAddress["nickname"] || "" }}</text> -->
          <text>{{ deliveryAddress[plang("username")]  || "" }}</text>
        </view>
        <view class="person-base">
          <image src="/static/mt-li/phone.png" />
          <text>{{ deliveryAddress.mobile || "" }}</text>
        </view>
      </view>

      <view class="address-squire">
        <view class="address">
          <view class="img-icon">
            <image src="/static/mt-li/fahuosss.png" mode="scaleToFill" />
          </view>
          <view class="flex-item">
            <view class="w100p name"> {{ $t("发货地址") }}: </view>
            <view class="w100p addres-desc">
              {{
                shippingAddress.address
                  ? shippingAddress[plang("address")]
                  : shippingAddress[plang("address1")]
              }}
            </view>
          </view>
        </view>
        <view class="address" @click="onChangeAddress">
          <view class="img-icon black">
            <image src="/static/mt-li/sending.png" mode="scaleToFill" />
          </view>
          <view class="flex-item">
            <view class="w100p name"> {{ $t("收货地址1") }}: </view>
            <view class="addres-desc" v-if="lang == 'zh'">
              {{
                (deliveryAddress[plang("mergename")] || "").split(",").join("")
              }}{{ deliveryAddress["xx_address"] }}
            </view>
            <view class="addres-desc" v-else>
              {{
                (deliveryAddress[plang("mergename")] || "").split(",").join(" ")
              }}
              {{ deliveryAddress["xx_address"] }}
            </view>
          </view>
        </view>

        <!-- 圆圈 -->
        <view class="circle-wrapper">
          <image src="/static/mt-li/down-la.png" mode="scaleToFill" />
        </view>
      </view>
    </view>
    <scroll-view scroll-y class="scroll-confirm">
      <!-- 待付款订单编号 -->
      <view class="good-wrapper">
        <view class="dt">{{ $t("待付款订单编号") }}:{{ ordernum }}</view>
        <view class="goods-lists">
          <view v-for="(item, index) in product" :key="index" class="good-w">
            <view class="good">
              <view class="img">
                <image
                  :src="
                    item.guige ? (item.guige[plang('pic')] || item.guige.pic) : (item[plang('pic')] || item.pic)
                  "
                  mode="aspectFill"
                />
                <!-- <view class="tag" >
									{{ item.is_yf == 1 ? $t('含运费1') : $t('不含运费') }}
								</view> -->
              </view>
              <view class="desc-w">
                <view class="name-w">
                  <view class="name ellipsis_two">{{
                    item[plang("name")]
                  }}</view>
                  <view class="num">x{{ item.num }}</view>
                </view>
                <template v-if="is_type == 0">
                  <view class="attr" v-if="item.guige">{{
                    item.guige[plang("name")]
                  }}</view>
                  <view class="price" v-if="item.guige"
                    ><text>{{ item.currency || '￥' }}</text
                    >{{
                      item.guige.qpsl <= item.num
                        ? item.guige.pf_price
                        : item.guige.sell_price
                    }}</view
                  >
                  <view class="price" v-else
                    ><text>{{ item.currency || '￥' }}</text
                    >{{
                      item.qpsl <= item.num
                        ? item.pf_price
                        : item.sell_price
                    }}</view
                  >
                </template>
                <template v-else>
                  <template v-if="skuInfo">
                    <view class="attr" v-if="skuInfo">{{
                      skuInfo[plang('attr_name')]
                    }}</view>
                    <view class="price"
                      ><text>{{ item.currency || '￥'}}</text
                      >{{ skuInfo.price }}</view
                    >
                  </template>
                  <template v-else>
                    <view class="attr" v-if="item.skuInfo">{{
                      item.skuInfo[plang('attr_name')]
                    }}</view>
                    <view class="price"
                      ><text>{{ item.currency || '￥'}}</text
                      >{{ item.skuInfo.price }}</view
                    >
                  </template>

                 
                </template>
              
              </view>
            </view>

            <!-- 商品信息 -->
            <template v-if="is_type != 1" >
              <view class="good-pejian" v-if="item.guige">
                <view class="item-good">
                  <view class="ti">{{ $t("单品体积") }}</view>
                  <view class="jian">{{ item.guige.volume || 0 }}m³</view>
                </view>
                <view class="item-good">
                  <view class="ti">{{ $t("单品重量") }}</view>
                  <view class="jian">{{ item.guige.weight || 0 }}kg</view>
                </view>
                <view class="item-good">
                  <view class="ti">{{ $t("单品密度") }}</view>
                  <view class="jian">{{ item.guige.midu || 0 }}kg/m³</view>
                </view>
              </view>
              <view class="good-pejian" v-else>
                <view class="item-good">
                  <view class="ti">{{ $t("单品体积") }}</view>
                  <view class="jian">{{ item.volume || 0 }}m³</view>
                </view>
                <view class="item-good">
                  <view class="ti">{{ $t("单品重量") }}</view>
                  <view class="jian">{{ item.weight || 0 }}kg</view>
                </view>
                <view class="item-good">
                  <view class="ti">{{ $t("单品密度") }}</view>
                  <view class="jian">{{ item.midu || 0 }}kg/m³</view>
                </view>
              </view>
            </template>
          </view>
        </view>
      </view>

      <!-- <view class="method-send" v-if="info.frType == 1">
				<view class="ti">{{ $t("商品已包含运费") }}</view>
			</view> -->
      <!-- <template v-if="info.frType == 2">
				<view class="method-send" @click="onSendMethod">
					<view class="ti">
						{{ getOpDesc() }}
					</view>
					<image src="/static/mt-li/youce.png" />
				</view>
				<view class="method-send">
					<view class="ti">{{ $t("此订单中部分商品包含运费") }}</view>
				</view>
			</template> -->

      <template>
        <view class="method-send" @click="onSendMethod">
          <view class="ti">
            {{ getOpDesc() }}
          </view>
          <image src="/static/mt-li/youce.png" />
        </view>
      </template>

      <!-- 银行账户 -->
      <view class="bank-wrapper">
        <!-- 总价 -->
        <view class="total-price">
          <view class="ti"
            >{{ $t("总价") }}<text>（{{ $t("包含手续费") }}）</text></view
          >
          <view class="price" v-if="skuInfo">
            <text>{{ product.length && product[0].currency || '￥'}}</text
            >{{ info.totalprice }}
          </view>
          <view class="price" v-else>
            <text>{{ product.length && product[0].currency || '￥'}}</text
            >{{ info.totalprice }}
          </view>
        </view>
        <!-- <view class="title">{{ $t("支付给") }}</view>
        <view class="bank" @click="bigImg">
          <image :src="urlImg" mode="widthFix" />
        </view> -->
      </view>
      <view style="height: 20rpx"></view>
    </scroll-view>

    <!-- 上传支付凭证 -->
    <view class="btn-w">
      <view class="btn" @click="onConfirmOrder"> {{ $t("提交订单") }} </view>
      <view style="height: 24rpx"></view>
    </view>

    <!-- 选择发货方式 -->
    <u-popup
      mode="bottom"
      border-radius="24"
      v-model="showPayPop"
      class="custom-popup"
    >
      <view class="pop-wrapper">
        <view class="title">{{ $t("选择发货方式") }}</view>
        <view class="container-pop">
          <view class="forient-fu" @click="changeFreightTypes(1)">
            <view class="ti">{{ $t("买家自提") }}</view>
            <image
              v-if="freightTypeCurrentNew == 1"
              src="/static/mt-li/group-ra.png"
            />
            <image v-else src="/static/mt-li/group-ra-no.png" />
          </view>
          <!-- 运费 -->
          <view class="forient-fu" @click="changeFreightTypes(2)">
            <view class="ti">{{ $t("商家发货") }}</view>
            <image
              v-if="freightTypeCurrentNew == 2"
              src="/static/mt-li/group-ra.png"
            />
            <image v-else src="/static/mt-li/group-ra-no.png" />
          </view>
          <!-- 代运输服务 -->
          <view class="yunshu-service" v-if="false">
            <view class="yunshu-title" @click="changeFreightType(1)">
              <view class="ti">{{ $t("商家代运输服务") }}</view>
              <image
                v-if="freightTypeCurrent == 2"
                src="/static/mt-li/group-ra.png"
              />
              <image v-else src="/static/mt-li/group-ra-no.png" />
            </view>
            <view v-if="freightTypeCurrent == 2" class="container-w">
              <view class="lists">
                <view
                  :class="['list', index === currentFuwuIndex && 'active']"
                  v-for="(item, index) in fuwu"
                  :key="item.id"
                  @click="onFuwuOption(index, item.id)"
                >
                  {{ item[plang("name")] }}
                  <view class="optioned" v-if="index === currentFuwuIndex">
                    <image src="/static/mt-li/duihao.png" />
                  </view>
                </view>
              </view>
              <view class="price-desc-compu">
                <view class="left-desc">
                  <view class="h1">{{
                    $t("根据您的收货地址与运输方式预估本次运输费用为")
                  }}</view>
                </view>
                <view class="prce-w">
                  <view class="fee">{{
                    $t("预估费用完全覆盖运费，无二次收费")
                  }}</view>
                  <view class="price">
                    <text>{{ unit() }}</text
                    >{{ freightObj[plang("yf_price")] }}
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view class="btn-w">
            <view class="btn" @click="onFreightConfirm">
              {{ $t("确定2") }}
            </view>
          </view>
        </view>
      </view>
    </u-popup>

    <!-- 请上传支付凭证 -->
    <u-popup
      border-radius="24"
      v-model="showPayPingzheng"
      class="custom-popup-pay"
      mode="bottom"
    >
      <view class="pingzheng-wrapper">
        <view class="title">{{ $t("请上传支付凭证") }}</view>

        <!-- 预览图片 -->

        <u-upload
          ref="uploadRef"
          :action="getUrl()"
          :auto-upload="true"
          :custom-btn="true"
          class="upload-wrapper"
          :show-upload-list="showUploadList"
          :deletable="false"
          @on-success="onSuccess"
          :form-data="{
            aid: 1,
          }"
        >
          <view slot="addBtn">
            <view
              class="pre-box"
              v-if="!showUploadList && imgPingzheng"
              @click="onOpenFile"
            >
              <image
                class="pre-item-image"
                :src="imgPingzheng"
                mode="aspectFill"
              ></image>
            </view>
            <view class="add-wrapper" v-show="!imgPingzheng">
              <image src="/static/mt-li/add.png" />
              <view class="txt">{{ $t("上传支付凭证") }}</view>
              <view class="desc">{{ $t("支持pdf、jpg、png格式") }}</view>
            </view>
          </view>
        </u-upload>

        <view class="btn-w">
          <view class="btn" @click="onPayPic"> {{ $t("确定2") }} </view>
          <view class="pay-desc">
            {{
              $t(
                "注意：提交上传后不可修改、撤回。为防止意外情况，请确保无误后上传"
              )
            }}
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import CommonHeader from "../components/common-header.vue";
import { HTTP_SHOPPING_URL, HTTP_REQUEST_URL } from "@/config/app";

import { scorePayment } from "@/api/basic";
import { ShoporderCreateOrder } from "@/api/freight";

let isSubmit = false;

export default {
  components: {
    CommonHeader,
  },
  data() {
    return {
      orderparams: null,
      shippingAddress: {}, // 发货地址
      deliveryAddress: {}, // 收货地址
      product: [], // 商品列表
      dfgs: {}, // 支付信息
      fuwu: [], // 服务
      showPayPop: false,
      showPayPingzheng: false,
      ordernum: "", // 订单编号

      // 上传
      showUploadList: false,
      lists: [],

      imgPingzheng: "",
      orderParamsSub: {
        aid: 1,
        ordernum: "",
        freighttype: "",
        linkman: "",
        tel: "",
        xx_address: "",
        area: "",
        area2: "",
        yfdf: "",
        fw_id: "",
        zfpz: "",
        buydata: "",
        isShopSend: "",
      },
      currentFuwuIndex: null,
      info: {},
      // 运费类型
      freightTypeCurrent: null, // 0 自行发货 1 运费到付 2 代运输服务
      isConfirmfreightTypeCurrent: null,

      freightObj: {
        yf_price: 0,
        yf_price_ru: 0,
      }, //运费对象
      lang: "",
      dfgsNewBank: {},
      freightTypeCurrentNew: 0, // 货代当前
      urlImg: "",
      is_type: 0,
      skuInfo: null,
      cart_id: "",
    };
  },

  methods: {
    bigImg() {
      uni.previewImage({
        urls: [this.urlImg],
        current: this.urlImg,
      });
    },
    getImg() {
      scorePayment({}).then((res) => {
        this.urlImg = res.data.data.img;
      });
    },
    // 获取发货方式选择描述
    getOpDesc() {
      // let desc = '';
      // if (this.isConfirmfreightTypeCurrent === 0) { // 自行发货
      // 	desc += this.$t('自行发货，无需商家发货');
      // } else if (this.isConfirmfreightTypeCurrent === 1) {
      // 	desc += this.$t('自行承担运费,由商家负责发货，运费到付');
      // } else if (this.isConfirmfreightTypeCurrent === 2) {
      // 	if (this.currentFuwuIndex != null) {
      // 		desc += this.$t('商家代运输服务') + '--' + this.fuwu[this.currentFuwuIndex][this.plang('name')];
      // 	}
      // } else {
      // 	desc += this.$t("选择发货方式");
      // }

      // return desc;

      let desc = "";
      if (this.orderParamsSub.isShopSend == 1) {
        // 自行发货
        desc += this.$t("买家自提");
      } else if (this.orderParamsSub.isShopSend == 2) {
        desc += this.$t("商家发货");
      } else {
        desc += this.$t("选择发货方式");
      }
      return desc;
    },
    // 确定发货类型
    onFreightConfirm() {
      this.showPayPop = false;
      // this.isConfirmfreightTypeCurrent = this.freightTypeCurrent; // 是否确认运费类型
      // this.getData();
      this.orderParamsSub.isShopSend = this.freightTypeCurrentNew;
    },
    // 切换运费类型
    changeFreightType(type) {
      if (this.freightTypeCurrent == type) {
        this.freightTypeCurrent = null;
        return;
      }
      this.freightTypeCurrent = type; // 运输类型
      if (type == 0) {
        this.orderParamsSub.freighttype = 3;
        this.orderParamsSub.yfdf = "";
        this.orderParamsSub.fw_id = null;
        this.currentFuwuIndex = 0;
      } else if (type == 1) {
        this.orderParamsSub.yfdf = 1;
        this.orderParamsSub.freighttype = "";
        this.orderParamsSub.fw_id = null;
        this.currentFuwuIndex = 0;
      } else if (type == 2) {
        this.currentFuwuIndex = 0;
        this.orderParamsSub.fw_id = this.fuwu[0].id;
        this.orderParamsSub.yfdf = "";
        this.orderParamsSub.freighttype = "";
      }
      this.getData(true);
    },
    // 类型 isShopSend 1 是自提 2 是商家发货
    changeFreightTypes(index) {
      if (this.freightTypeCurrentNew == index) {
        this.freightTypeCurrentNew = "";
      } else {
        this.freightTypeCurrentNew = index;
      }
    },
    // 提交订单
    async onConfirmOrder() {
      // 收货地址校验
      if (!this.orderParamsSub.area) {
        uni.showToast({
          title: this.$t("请选择所在地区"),
          icon: "none",
        });
        return;
      }

      if (!this.orderParamsSub.isShopSend) {
        uni.showToast({
          title: this.$t("选择发货方式"),
          icon: "none",
        });
        return;
      }

      if (isSubmit) {
        return;
      }
      isSubmit = true;
      try {
        uni.showLoading({
          title: this.$t("提交"),
          mask: true,
        });
        let arr = [];
        if (this.is_type == 1){ // 1688
          this.info.product.forEach((ele) => {
            arr.push({
              product_id: ele.id,
              name: ele.name,
              pic: ele.pic,
              num: ele.num,
              ggid: ele.sku_id,
              ggname: this.skuInfo ? this.skuInfo.attr_name : ele.skuInfo.attr_name,
              unit: ele.sldw,
              cost_price: this.skuInfo ? this.skuInfo.price : ele.skuInfo.price,
              totalprice: this.info.totalprice,
              cid: ele.cid,
              is_type: this.is_type,
            });
          });
        } else {
          this.info.product.forEach((ele) => {
            if (ele.guige) {
              arr.push({
                product_id: ele.id,
                name: ele.name,
                pic: ele.guige.pic,
                num: ele.num,
                ggid: ele.guige.id,
                ggname: ele.guige.name,
                unit: ele.sldw,
                cost_price:
                  ele.guige.qpsl <= ele.num
                    ? ele.guige.pf_price
                    : ele.guige.sell_price,
                totalprice: this.info.totalprice,
                cid: ele.cid,
              });
            } else {
              arr.push({
                product_id: ele.id,
                name: ele.name,
                pic: ele.pic,
                num: ele.num,
                ggid: 0,
                ggname: "",
                unit: ele.sldw,
                cost_price: ele.qpsl <= ele.num ? ele.pf_price : ele.sell_price,
                totalprice: this.info.totalprice,
                cid: ele.cid
              });
            }
          });
        }
       
        //
        let res = await ShoporderCreateOrder({
          user_id: uni.getStorageSync("user_id"), // 用户id
          pre_user_id: this.shippingAddress.mid, // 商户userid
          destination:
            this.orderParamsSub.area + (this.orderParamsSub.xx_address || ''), // 收货地址
          city_info: this.orderParamsSub.area2, // 城市信息
          mailing_type: this.orderParamsSub.isShopSend || "", // 邮寄方式 1自提 2发货
          json_shop_data: JSON.stringify(arr),
					address: this.shippingAddress.address || this.shippingAddress["address1"],
          cart_id: this.cart_id || ""
        });
     
        if (res.data.code == 200) {
          uni.hideLoading({});
          setTimeout(() => {
            uni.showToast({
              title: this.$t("提交成功"),
            });
						setTimeout(() => {
							isSubmit = false;
							uni.redirectTo({
								url: "/pages/shopOrder/order/index",
							});
						}, 300);
         
          }, 300);
        } else {
					isSubmit = false;
					uni.showToast({
						title: res.data[this.plang('message')],
						icon: "none",
					});
        }
      } catch (error) {
        isSubmit = false;
      }
    },
    // 更新收货地址
    onUpdateAddress(info) {
      this.deliveryAddress = {
        ...this.deliveryAddress,
        ...info,
      };

      this.orderParamsSub.linkman = info.username;
      this.orderParamsSub.tel = info.mobile;
      this.orderParamsSub.xx_address = info.xx_address;
      this.orderParamsSub.area = info.mergename;
      this.orderParamsSub.area2 = info.area_id;
    },
    // 确认支付凭证
    onPayPic() {
      if (!this.imgPingzheng) {
        uni.showToast({
          title: this.$t("请上传支付凭证"),
          icon: "none",
        });
        return;
      }
      this.orderParamsSub.zfpz = this.imgPingzheng;
      this.showPayPingzheng = false;
    },
    onFuwuOption(index, id) {
      this.currentFuwuIndex = index;
      this.orderParamsSub.fw_id = id;
      this.getData(true);
    },
    // 选择发货方式
    onSendMethod() {
      this.showPayPop = true;
    },
    goback() {
      uni.navigateBack({
        delta: 1,
      });
    },
    async getData(isPartialUpdate = false, init) {
      // isPartialUpdate 局部更新 只更新 运输费用
      try {
        if (this.orderParamsSub.fw_id) {
          if (this.freightTypeCurrent == null) {
            this.orderparams.fw_id = "";
          } else {
            this.orderparams.fw_id = this.orderParamsSub.fw_id;
          }
        } else {
          this.orderparams.fw_id = "";
        }
        const res = await this.$u.api.shopping.confimrOrder(this.orderparams);

        if (!isPartialUpdate) {
          this.product = res.data.product;
          res.data.user = res.data.user || {};
          res.data.userinfo = res.data.userinfo || {};

          this.shippingAddress = res.data.business || {};
          this.dfgs = res.data.dfgs || {};
          this.dfgsNewBank = res.data.dfgsNewBank || {};
          this.ordernum = res.data.ordernum;
          // 服务集团
          this.fuwu = res.data.fuwu || [];
          this.info = res.data;

          if (init) {
            this.deliveryAddress = {
              username: res.data.user.username,
              username_ru:res.data.user.username_ru,
              mobile: res.data.user.mobile,
              ...res.data.userinfo,
            };
            // 设置提交参数
            this.orderParamsSub.ordernum = res.data.ordernum;
            this.orderParamsSub.buydata = this.orderparams.prodata;
            this.orderParamsSub.linkman = res.data.user.username;
            this.orderParamsSub.tel = res.data.user.mobile;
            this.orderParamsSub.xx_address = res.data.userinfo.xx_address;
            this.orderParamsSub.area = res.data.userinfo.mergename;
            this.orderParamsSub.area2 = res.data.userinfo.area_id;
          }
        }
        this.freightObj.yf_price = res.data.yf_price;
        this.freightObj.yf_price_ru = res.data.yf_price_ru;
        this.orderParamsSub.bid = this.orderparams.bid;
        if (this.skuInfo) {
          res.data.product.forEach(item => {
            this.info[this.plang("totalprice")] = (this.skuInfo.price *  item.num).toFixed(2)

          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    async onPay() {
      uni.navigateTo({
        url: "/pages/proofPayment/index",
      });
    },
    onUploadPingzheng() {
      this.showPayPingzheng = true;
    },

    // 银行卡号分割
    formatCardNumber(cardNumber) {
      if (!cardNumber) {
        return;
      }
      // 去除空格
      cardNumber = cardNumber.replace(/\s+/g, "");
      // 使用 slice 分割
      const formatted = [];
      for (let i = 0; i < cardNumber.length; i += 4) {
        formatted.push(cardNumber.slice(i, i + 4));
      }

      return formatted.join(" "); // 以空格连接
    },
    onCopy(card) {
      uni.setClipboardData({
        data: card,
        success: () => {
          uni.showToast({
            title: this.$t("复制成功"),
          });
        },
      });
    },
    // 修改地址
    onChangeAddress() {
      uni.setStorageSync('addressInfo', this.deliveryAddress)
      uni.navigateTo({
        url:
          "/pages/ShippingAddress/index",
      });
    },
    // 图片上传成功
    onSuccess(e) {
      this.imgPingzheng = e.url;
    },
    onChange(e) {
    },

    getUrl() {
      return process.env.NODE_ENV == "development"
        ? "/api/?s=ApiImageupload/uploadImg"
        : HTTP_SHOPPING_URL + "/?s=ApiImageupload/uploadImg";
    },
    onOpenFile() {
      this.$refs.uploadRef.clear();

      this.$refs.uploadRef.upload();
    },
  },
  onReady() {},

  onLoad({ info, is_type,skuInfo,cart_id }) {
    this.cart_id = cart_id || ""
    this.getImg();
    this.orderparams = JSON.parse(info);
    this.getData(false, true);
    this.is_type = is_type || 0;

    if (skuInfo) {
      this.skuInfo = JSON.parse(skuInfo);
    }

    this.lang = uni.getStorageSync("lang");
    window.onNativeShow = () => {
      if (uni.getStorageSync("onUpdateAddress")) {
        this.onUpdateAddress(JSON.parse(uni.getStorageSync("onUpdateAddress")));
      }
    };
    window.onNativeHide = () => {
      uni.removeStorageSync("onUpdateAddress");
    };
  },
  onShow() {},
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
